# -*- coding: utf-8

from django.shortcuts import render
from .models import Address
from django.views.decorators.http import require_http_methods
from api.views import error, render

# Create your views here.
@require_http_methods(["POST"])
def address_create(request):
    '''
        'customer.address.create'
        create a new tiny shop
    '''
    mobile_no =  request.session.get('mobile_no')
    if mobile_no == None:
        return error(u'登陆无效')
    
    name = request.POST.get('name')
    province = request.POST.get('province')
    city = request.POST.get('city', "")
    address = request.POST.get('address')
    tel = request.POST.get('tel')
    
    address = Address(
                      name=name, 
                      province=province,
                      city=city,
                      address=address,
                      tel=tel,
                      owner=mobile_no,
                      )
    address.save()
    return render({ "address": address })

@require_http_methods(["POST"])
def address_remove(request):
    '''
        address delete
    '''
    address_id = request.POST.get('address_id')
    mobile_no = request.session.get('mobile_no')

    try:
        add = Address.objects.get(pk=address_id)
    except:
        return error(u'地址不存在！')
    
    if mobile_no != add.owner:
        return error(u'访问错误')
    
    add.delete()
    return render({ "address": add })

@require_http_methods(["GET"])
def address_list(request):
    mobile_no =  request.session.get('mobile_no')
    if mobile_no == None:
        return error(u'登陆无效')
    
    addresses = Address.objects.filter(owner=mobile_no)

    return render({"addresses": addresses})


@require_http_methods(["GET"])
def order_list(request):
    mobile_no =  request.session.get('mobile_no')
    if mobile_no == None:
        return error(u'登陆无效')
    
    orders = Order.objects.filter(payer=mobile_no)

    return render({"orders": orders})
